package com.shinhye.elephantsafe.service;

import java.util.List;

import com.shinhye.elephantsafe.WatchDogInterceptActivity;
import com.shinhye.elephantsafe.db.dao.ApplockDao;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class WatchDogService extends Service {
	private final String TAG = "WatchDogService";
	private ActivityManager am;
	private List<String> packNameList;
	private StopLockReceiver stopLockReceiver;
	private String stopLockPackName;
	private boolean flag;
	private LockScreenReceiver lockScreenReceiver;
	private ApplockDao dao;
	private AppLockContentObserver observer;
	private Thread subThread;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	/**
	 * A receiver to stop locking specified APP. 
	 * @author ShinHye
	 *
	 */
	class StopLockReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			Log.i(TAG, "看门狗收到暂时停止对某一程序保护的消息！");
			stopLockPackName = intent.getStringExtra("packagename");
		}
	}
	
	/**
	 * Receiver the lock screen broadcast to start or stop run WatchDog.
	 * @author ShinHye
	 *
	 */
	private class LockScreenReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if(Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
				Log.i(TAG, "收到锁屏广播了！停止WatchDog！");
				flag = false;
				stopLockPackName = "";
			} else if(Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
				Log.i(TAG, "收到锁屏广播了！启动WatchDog！");
				runWatch();
			}
			
		}
	}
	
	/**
	 * A ContentObserver of AppLock database. 
	 * @author ShinHye
	 *
	 */
	private class AppLockContentObserver extends ContentObserver {
		public AppLockContentObserver(Handler handler) {
			super(handler);
		}
		@Override
		public void onChange(boolean selfChange) {
			Log.i(TAG, "AppLock数据库变化了！");
			packNameList = dao.findAll();
			if(!subThread.isAlive()) {
				runWatch();
				/**如果写subThread.start()会报错：subThread已经start过，从下图可以看出线程结束状态不能转向任何其他状态。
				 * 
				 *                    运行 ------> 结束   
					                  / \
					                 /   \
				 *  新建-------> 就绪<-----阻塞
				 *  
				 *  如果写subThread.run()执行会导致界面ANR。大概也是因为结束状态不能转回运行状态，所以有问题。只能new一个新线程。
				 */
			}
		}
	}
	
	@Override
	public void onCreate() {
		Log.i(TAG, "看门狗服务开启了！");
		
		dao = new ApplockDao(this);
		packNameList = dao.findAll();
		
		stopLockReceiver = new StopLockReceiver();
		IntentFilter stopFilter = new IntentFilter("com.shinhye.elephantsafe.stoplockapp");
		registerReceiver(stopLockReceiver, stopFilter);
		
		//注册一个内容观察者
		Uri uri = Uri.parse("content://com.shinhye.elephantsafe.applockdb");
		observer = new AppLockContentObserver(new Handler());
		getContentResolver().registerContentObserver(uri, true, observer);
		
		lockScreenReceiver = new LockScreenReceiver();
		IntentFilter screenFilter = new IntentFilter();
		screenFilter.addAction(Intent.ACTION_SCREEN_ON);
		screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
		registerReceiver(lockScreenReceiver, screenFilter);
		
		am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		runWatch();
	}
	
	public void runWatch() {
		subThread = new Thread(new Runnable(){
			@Override
			public void run() {
				flag = true;
				while(flag) {
					if(packNameList.size() == 0) {
						Log.i(TAG, "没有加锁的程序，看门狗停止运行！");
						break;
					}
					Log.i(TAG, packNameList+"看门狗运行中！"+Thread.activeCount());
					RunningTaskInfo taskInfo = am.getRunningTasks(1).get(0);
					String packName = taskInfo.baseActivity.getPackageName();
					if(packNameList.contains(packName)) {
						if(packName.equals(stopLockPackName)) {
							Log.i(TAG, "该程序刚刚输入了密码，看门狗放行！");
							//Nothing
						} else {
							Intent intent = new Intent(WatchDogService.this, WatchDogInterceptActivity.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							intent.putExtra("packname", packName);
							startActivity(intent);
						}
					}
					
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			};
		});
		
		subThread.start();

	}
	
	@Override
	public void onDestroy() {
		Log.i(TAG, "看门狗服务关闭了！");
		flag = false;
		
		unregisterReceiver(stopLockReceiver);
		stopLockReceiver = null;
		
		unregisterReceiver(lockScreenReceiver);
		lockScreenReceiver = null;
		
		//解注册内容观察者
		getContentResolver().unregisterContentObserver(observer);
		observer = null;
	}
}
